package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.farmrecords.enums.FarmRecordsFileEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.mapper.FarmRecordsFileMapper;
import com.dongjiantong.farmrecords.mapper.FarmRecordsIntroduceMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsFile;
import com.dongjiantong.farmrecords.model.FarmRecordsIntroduce;
import com.dongjiantong.farmrecords.service.FarmRecordsFileService;
import com.dongjiantong.farmrecords.service.FarmRecordsIntroduceService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.user.enums.FarmsEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采购中心-引种记录
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsIntroduceServiceImpl extends ServiceMybatis<FarmRecordsIntroduce> implements FarmRecordsIntroduceService {

    @Resource
    private FarmRecordsIntroduceMapper farmRecordsIntroduceMapper;
    @Resource
    private FarmRecordsFileMapper farmRecordsFileMapper;

    @Resource
    private FarmRecordsFileService farmRecordsFileService;

    @Override
    public PageInfo<FarmRecordsIntroduce> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsIntroduceMapper == null){
                throw new OPServerException("farmRecordsIntroduceMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsIntroduce> farmRecordsIntroduceList = farmRecordsIntroduceMapper.selectByMap(map);

            if (farmRecordsIntroduceList.size() > 0){
                this.setPicOrVideoList(farmRecordsIntroduceList);
            }

            return new PageInfo<FarmRecordsIntroduce>(farmRecordsIntroduceList);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 设置关联信息(视频,图片)
     * @param farmRecordsIntroduceList
     */
    public void setPicOrVideoList(List<FarmRecordsIntroduce> farmRecordsIntroduceList){
        if (farmRecordsFileMapper == null){
            throw new OPServerException("farmRecordsFileMapper 为null,请检查");
        }
        List<Long> ids = farmRecordsIntroduceList.stream().map(farmRecordsIntroduce -> farmRecordsIntroduce.getId()).collect(Collectors.toList());

        List<Integer> type2List = Lists.newArrayList(FarmRecordsFileEnum.PHOTO.getCode(),FarmRecordsFileEnum.VIDEO.getCode());

        Map map = Maps.newHashMap();
        map.put("relevanceIds",ids);
        map.put("listType2",type2List);
        map.put("type1",FarmRecordsFileEnum.INTRODUCE.getCode());
        //查询对应的图片,视频
        List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileMapper.selectPicOrVideoListByRelevanceIds(map);

        if (farmRecordsFileList.size() > 0){
            for (FarmRecordsIntroduce farmRecordsIntroduce : farmRecordsIntroduceList){
                this.setPicOrVideoByObj(farmRecordsIntroduce,farmRecordsFileList);
            }
        }
    }

    @Override
    public FarmRecordsIntroduce setPicOrVideoByObj(FarmRecordsIntroduce farmRecordsIntroduce,List<FarmRecordsFile> farmRecordsFileList) {
        List<String> picList = Lists.newArrayList();
        List<String> videoList = Lists.newArrayList();
        for (FarmRecordsFile farmRecordsFile : farmRecordsFileList){
            if ((farmRecordsIntroduce.getId()).equals(farmRecordsFile.getRelevance_id())){
                JSONArray jsonArray = JSON.parseArray(farmRecordsFile.getAddress());
                List<String> list = jsonArray.toJavaList(String.class);
                //获取图片
                if ((FarmRecordsFileEnum.PHOTO.getCode()).equals(farmRecordsFile.getType2())){
                    picList = list;
                }
                //获取视频
                if ((FarmRecordsFileEnum.VIDEO.getCode()).equals(farmRecordsFile.getType2())){
                    videoList = list;
                }
            }
        }
        //设置图片
        if (picList.size() > 0){
            farmRecordsIntroduce.setPicList(picList);
        }
        //设置视频
        if (videoList.size() > 0){
            farmRecordsIntroduce.setVideoList(videoList);
        }

        return farmRecordsIntroduce;
    }

    /**
     * 新建一条记录 (暂存状态下)
     * @param farmRecordsIntroduce
     * @param toStatus
     * @return  long 返回插入数据的id
     */
    @Override
    public Long createOne(LoginInfo loginInfo,FarmRecordsIntroduce farmRecordsIntroduce, Integer toStatus) {
        int id = 0;
        try {
            if (farmRecordsIntroduceMapper == null){
                throw new OPServerException("farmRecordsIntroduceMapper 为null,请检查");
            }
            Integer fromStatus = farmRecordsIntroduce.getStatus();

            //todo 生成单据号
            //单据生成规则暂未定(此处为测试)
            String prefix = "CYZ";
            prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
            String maxNumber = farmRecordsIntroduceMapper.findMaxNumber(prefix);
            String number = ReportNumberMakerUtil.create(prefix,maxNumber);
            farmRecordsIntroduce.setNumber(number);

            farmRecordsIntroduce.setProvince_id(loginInfo.getProvinceId());
            farmRecordsIntroduce.setCity_id(loginInfo.getCityId());
            farmRecordsIntroduce.setRegion_id(loginInfo.getRegionId());
            farmRecordsIntroduce.setStreet_id(loginInfo.getRegionId());
            farmRecordsIntroduce.setVillage_id(loginInfo.getVillageId());

            farmRecordsIntroduce.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

            if (fromStatus == 0 && toStatus == null) {
                //直接暂存
                farmRecordsIntroduceMapper.createOne(farmRecordsIntroduce);
            }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)) {
                //直接提交
                farmRecordsIntroduce.setStatus(toStatus);
                farmRecordsIntroduceMapper.createOne(farmRecordsIntroduce);
            }

            if (farmRecordsIntroduce.getId() != null) {
                farmRecordsFileService.insertPicOrVideoByRelevanceId(FarmRecordsFileEnum.INTRODUCE.getCode(),farmRecordsIntroduce.getPicList(),farmRecordsIntroduce.getVideoList(),farmRecordsIntroduce.getId());
            }

            //todo 生成政府操作记录

            return farmRecordsIntroduce.getId();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_CREATE_FAIL,HttpCode.DATA_CREATE_FAIL.getMessage());
        }
    }

    /**
     * 更新一条记录 (根据id或者number)
     * @param farmRecordsIntroduce
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @Override
    public Integer updateByIdOrNumber(FarmRecordsIntroduce farmRecordsIntroduce,Integer toStatus) {
        try {
            if (farmRecordsIntroduceMapper == null){
                throw new OPServerException("farmRecordsIntroduceMapper 为null,请检查");
            }
            farmRecordsIntroduce.setStatus(toStatus);
            farmRecordsIntroduce.setUpdated_at(new Date());
            Integer con = farmRecordsIntroduceMapper.updateByPrimaryKeySelective(farmRecordsIntroduce);

            farmRecordsFileService.updatePicOrVideoByRelevanceId(FarmRecordsFileEnum.INTRODUCE.getCode(),farmRecordsIntroduce.getPicList(),farmRecordsIntroduce.getVideoList(),farmRecordsIntroduce.getId());

            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }

    @Override
    public PageInfo<FarmRecordsIntroduce> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status != null) {
            map.put("status",status);
        }

        map.put("farm_id",farmId);
        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

        List<FarmRecordsIntroduce> farmRecordsIntroduceList = farmRecordsIntroduceMapper.selectListByStatus(map);

        if (farmRecordsIntroduceList.size() > 0) {
            this.setPicOrVideoList(farmRecordsIntroduceList);
        }

        return new PageInfo<FarmRecordsIntroduce>(farmRecordsIntroduceList);
    }

    /**
     * 根据养殖场id 和时间区间获取引种数量和总价
     * @param farmId
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public Map<String, Object> selectQuantityAndPrice(Long farmId, Date startDate, Date endDate) {
        if (farmId == null) {
            throw new OPServerException("养殖场id不能为空");
        }

        Map<String,Object> map = Maps.newHashMap();
        if (farmId != null) {
            map.put("farmId",farmId);
        }
        if (startDate != null) {
            map.put("startDate",startDate);
        }
        if (endDate != null) {
            map.put("endDate",endDate);
        }

        Map<String,Object> result = farmRecordsIntroduceMapper.selectQuantityAndPrice(map);
        return result;
    }
}
